const baseUrl = "http://localhost:8080";

/**
 * function: 封装网络请求
 * @url URL地址
 * @params 请求参数
 * @method 请求方式：GET/POST
 * @onSuccess 成功回调
 * @onFailed  失败回调
 */
function request(options) {
  const m = options.method;
  if (m) {
    if (m.toLowerCase() === "get") {
      wx.showLoading({
        title: "正在加载中...",
      });
    } else if (m.toLowerCase() === "post") {
      wx.showLoading({
        title: "请稍后...",
      });
    }
  }


  return new Promise((resolve, reject) => {
    wx.request({
      url: baseUrl + options.url,
      data: options.data,
      header: {"content-type": "application/x-www-form-urlencoded"},
      method: options.method,
      success: function (res) {
        resolve(res);
        wx.hideLoading();
        if (res.data.status_code == 401 && res.data.code == -101) {
          wx.showToast({
            title: res.data.message,
            icon: "none",
          });
        }
        if (res.statusCode === 406) {
          wx.showToast({
            title: res.data,
            icon: "none",
          });
        }
      },
      fail: function (error) {
        reject(error); //failure for other reasons
      },
    });
  });
}

// 通过module.exports方式提供给外部调用
module.exports = {
  request: request,
};
